﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IdeaNMR.Shared.Utils
{
    public static class UriBuilderExtensions
    {
        /// <summary>
        /// Adds a parameter to query string.
        /// </summary>
        /// <param name="ub"></param>
        /// <param name="paramName">Parameter Name</param>
        /// <param name="paramValue">Parameter Value</param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when <paramref name="paramName"/> is null or empty string.</exception>
        /// <remarks>
        /// <para>
        ///     The added parameter is of form 
        ///     <c><paramref name="paramName"/>=<paramref name="paramValue"/></c> 
        ///     if <paramref name="paramValue"/> is not null or empty.
        ///     Otherwise it is just <c><paramref name="paramName"/></c>.
        ///     A '&' char is added between parameters.
        /// </para>
        /// </remarks>
        public static void AddQueryParameter(this UriBuilder ub, string paramName, string paramValue)
        {
            if (string.IsNullOrEmpty(paramName))
                throw new ArgumentNullException("ParameterName must not be empty or null.");

            string para = string.IsNullOrEmpty(paramName) 
                                ? paramName 
                                : string.Format("{0}={1}", paramName, paramValue);

            ub.Query = (ub.Query != null && ub.Query.Length > 1)
                                ? string.Format("{0}&{1}", ub.Query.Substring(1), para)
                                : para;
        }
    }
}
